<?php
/**
 * (logic) fba库存（已弃用）
 */
namespace App\Logic\Amazon;

use App\Libs\FBAInventoryServiceMWS\InventoryMws;
use App\Libs\RequestClient;
use App\Models\Amazon\FBAInventory;
use App\Models\Basics\AmazonCountry;
use Illuminate\Support\Facades\DB;
class GrabInventory extends GrabCommon
{
    const GRAB_INVENTORY_INTERVAL = '-1 day';

    /**
     * 返回卖家库存状况信息。返回卖家位于 亚马逊物流 和在当前入库货件中的库存的供应情况相关信息。
     * API:ListInventorySupply
     * @param $account
     * @param array $con
     * @return array|bool
     */
    public static function listInventorySupply($account,$con = array()){
        if(!$account)return false;
        if(!(isset($con['QueryStartDateTime']) && $con['QueryStartDateTime'])){
            $con['QueryStartDateTime'] = self::_getQueryStartDateTime();
        }
        if(!$con['QueryStartDateTime'])return false;
        $con['SellerId'] = $account->merchant;
        $con['MWSAuthToken'] = $account->mws_auth_token;
        $con['ResponseGroup'] = 'Detailed';//值：Basic-不包括响应中的SupplyDetail元素 Detailed-在响应中包含SupplyDetail元素 默认值：Basic
        $service = self::getRequestClient('inventory',$account);
        $rm = InventoryMws::getInit();
        $marketplaceIdList = $account->countries->pluck('marketplace_id')->toArray();
        $s = 0;
        $re = [];
        foreach ($marketplaceIdList as $marketplaceId){
            $con['MarketplaceId'] = $marketplaceId;
            $param = $rm->listInventorySupply($con);
            $data = $service->requestExe($param);
            if(!$data){
                $re[$marketplaceId] = false;
                continue;
            }
            $countryId = AmazonCountry::getCountryIdByMarketplaceId($marketplaceId);
            $nextToken = self::_extractListInventorySupplyResponse($account,$data,$countryId);
            self::_listInventorySupplyByNextToken($account,$service,$countryId,$nextToken);
            sleep(2);
            $s++;
            $re[$marketplaceId] = true;
        }
        return $re;
    }

    /**
     * 返回下一页卖家库存状况信息。
     * API ListInventorySupplyByNextToken
     * @param $account
     * @param $service
     * @param $countryId
     * @param $nextToken
     */
    private static function _listInventorySupplyByNextToken($account,$service,$countryId,$nextToken){
        if($nextToken){
            sleep(1);
            if(!($service instanceof RequestClient)){
                $service = self::getRequestClient('inventory',$account);
            }
            $rm = InventoryMws::getInit();
            $param = $rm->listInventorySupplyByNextToken(['SellerId'=>$account->merchant,'NextToken'=>$nextToken,'MWSAuthToken' => $account->mws_auth_token]);
            $data = $service->requestExe($param);
            $nextToken = self::_extractListInventorySupplyResponse($account,$data,$countryId,true);
            self::_listInventorySupplyByNextToken($account,$service,$countryId,$nextToken);
        }
    }

    private static function _extractListInventorySupplyResponse($account,$data,$countryId,$flag = false){
        $_str = $flag ? 'ListInventorySupplyByNextTokenResult' : 'ListInventorySupplyResult';
        $response = isset($data[$_str]['InventorySupplyList']['member']) ? $data[$_str]['InventorySupplyList']['member'] : [];
        if(isset($response['SellerSKU']))$response = [$response];
        self::_extractMembers($account,$response,$countryId);
        return isset($data[$_str]['NextToken']) ? $data[$_str]['NextToken'] : null;
    }

    private static function _extractMembers($account,$members,$countryId){
        try{
            DB::connection('mysql_amazon')->beginTransaction();
            foreach($members as $member){
                if(!$member['SellerSKU'])continue;
                $item = [];
                $item['account_id'] = $account->id;
                $item['country_id'] = $countryId;
                $item['seller_sku'] = $member['SellerSKU'];
                $item['asin'] = $member['ASIN'];
                $item['fnsku'] = $member['FNSKU'];
                $item['total_supply_quantity'] = $member['TotalSupplyQuantity'];
                $item['instock_supply_quantity'] = $member['InStockSupplyQuantity'];
                $item['inbound_supply_quantity'] = isset($member['SupplyDetail']) ? self::_extractSupplyDetail($member['SupplyDetail']) : 0;
                self::_store($item);
            }
            DB::connection('mysql_amazon')->commit();
        }catch (\Exception $e){
            DB::connection('mysql_amazon')->rollBack();
            report($e);
        }
    }

    private static function _extractSupplyDetail($supplyDetail){
        if(!$supplyDetail)return 0;
        $_member = isset($supplyDetail['member']) ? $supplyDetail['member'] : [];
        if(isset($supplyDetail['SupplyType']))$_member = [$_member];
        $sum = 0;
        foreach ($_member as $_item){
            if($_item['SupplyType'] == 'Inbound') $sum += $_item['Quantity'];
        }
        return $sum;
    }

    private static function _store($item){
        FBAInventory::create($item);
    }

    private static function _getQueryStartDateTime(){
        $queryStartDateTime = strtotime(date('Y-m-d',strtotime(self::GRAB_INVENTORY_INTERVAL)));
        $queryStartDateTimeMax = time() - 120;
        $time = min($queryStartDateTime,$queryStartDateTimeMax);
        return getDateFormat(date('Y-m-d H:i:s',$time - self::GRAB_ZONE_INTERVAL));
    }
}
